
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

import json,os,sys
from ctypes import *
from log import logger

protocol = {
    "profile" : None,
    "dll": None
}

class ProtocolSelectWidget(QComboBox):
    def __init__(self):
        super().__init__()
        
        listView = QListView()
        self.setView(listView)

        self.currentIndexChanged.connect(self.selectProtocol)

        # 获取protocol文件夹下所有的文件
        files = os.listdir("./protocol/")
        logger.info(files)

        # 将同名不同后缀的文件名单独挑出
        self.protocolList = {}
        for file in files:
            fileSplit = file.split(".")
            name = fileSplit[0]
            try:
                suffix = fileSplit[1]
            except Exception:
                continue
            logger.info(name + " " + suffix)
            if self.protocolList.get(name) is None:
                self.protocolList[name] = {
                    "profile": None,
                    "dll":None
                }
            self.protocolList[name][suffix] = file

        # 只添加 dll 和 profile 都全的
        for key in self.protocolList.keys():
            if self.protocolList[key]["dll"] is not None and self.protocolList[key]["profile"] is not None:
                self.addItem(key)
    

    # 只返回路径 TODO
    def selectProtocol(self):
        dllPath = os.path.abspath(os.curdir) + "\protocol\%s.dll" % self.currentText()
        protocol["dll"] = CDLL(dllPath)
        with open("protocol/%s.profile.json" % self.currentText(), "r", encoding="utf8") as f:
            protocol["profile"] = json.loads(f.read())


        logger.info("[Protocol] Load %s successfully, description is %s" % (
            c_char_p(protocol["dll"].name()).value.decode("gbk"),
            c_char_p(protocol["dll"].description()).value.decode("gbk")
        ))


    def currentDll(self):
        return protocol["dll"]
    
    def currentProfile(self):
        return protocol["profile"]
    
    def currentCmdList(self):
        return protocol["profile"]["cmdList"]
    
    def currentBaseInfo(self):
        return protocol["profile"]["baseInfo"]
    
    def findCmd(self, cmdType, cmdTarget):
        for cmd in self.currentCmdList().get(cmdType):
            if cmd.get("cmd") == cmdTarget:
                return cmd
        return None
    
    def currentProcess(self):
        return protocol["profile"]["processList"]